package org.doubango.FrCall;

import java.util.Collection;

import org.doubango.FrCall.Screens.BaseScreen;
import org.doubango.FrCall.model.SystemMessage;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.RosterListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Type;
import org.jivesoftware.smack.packet.RosterPacket.ItemType;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.widget.Toast;

public class OpenfireRosterService extends Service {
	private final static String TAG = OpenfireRosterService.class
			.getCanonicalName();
	public final static int REQUEST_REFRESH_FRIEND_LIST = 0;
	public final static int REQUEST_ADD_FRIEND = 1;
	public final static int REQUEST_DELETE_FRIEND = 2;
	public final static int REQUEST_SEARCH_FRIEND = 3;
	public final static int REQUEST_CHANGE_GROUP = 4;
	public static Roster roster;
	public XMPPConnection mConnection;
    public interface ICountService {
    	public abstract int getCount();
    }
    private ServiceBinder serviceBinder=new ServiceBinder();
    public class ServiceBinder extends Binder implements ICountService{
    	@Override
    	public int getCount() {
    		return 0;
    	}        
    }
	BroadcastReceiver br = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent.getAction().equals(getResources().getString(R.string.OPENFIRE_ACTION_REQ_LOGIN)))
			{
			}
		}
	};
	public RosterListener rosterListener = new RosterListener() {

		@Override
		public void entriesAdded(Collection<String> addresses) {
			System.out.println("entriesAdded");
			roster.reload();
//			toastText+="添加";
//			ListHander.sendEmptyMessage(SCREEN_HOME_HANDLE_TOAST_SHOW_LIST);
//			getFriends();
//			adapter.notifyDataSetChanged();
		}

		@Override
		public void entriesUpdated(Collection<String> addresses) {
			System.out.println("entriesUpdated");
//			toastText ="";
//			for(String address :addresses)
//			{
//				Presence pre = new Presence(Type.subscribed);
//				pre.setFrom(BangBangChat.s_MyUserID);
//				pre.setTo(address);
//				mOpenfireService.getXMPPConnection().sendPacket(pre);
//				toastText +=address+","; 
//			}
			for(String address :addresses)
			{
				if(!roster.contains(address))
					continue;
				RosterEntry ros=roster.getEntry(address);
				if(ros.getType()==ItemType.remove)
				{
					try {
						roster.removeEntry(ros);
					} catch (XMPPException e) {
						e.printStackTrace();
					}
				}
			}
//			refreshlist();	
			NotifyRefreshList();
		}

		@Override
		public void entriesDeleted(Collection<String> addresses) {
			System.out.println("entriesDeleted");
//			for(String address :addresses)
//			{
//				if(!roster.contains(address))
//					continue;
//				RosterEntry ros=roster.getEntry(address);
//				try {
//					roster.removeEntry(ros);
//				} catch (XMPPException e) {
//					e.printStackTrace();
//				}
//			}
			roster.reload();
//			refreshlist();
		}

		@Override
		public void presenceChanged(Presence presence) {
			System.out.println(presence.getFrom()+" is "+presence.getType()+" presenceChanged - >" + presence.getStatus());

//			if(!presence.getType().equals(Type.unavailable))
			{
				
 				needRefreshList = false;
 				if((presence.getType() == (Type.available)))
 				{
 					RosterEntry ros = roster.getEntry(presence.getFrom().substring(0, presence.getFrom().indexOf("/")));
	 				toastText = ros.getUser()+presence.getStatus();
//	 				ListHander.sendEmptyMessage(SCREEN_HOME_HANDLE_TOAST_SHOW_LIST);
//	 				getEngine().getSoundService().startNewComing();
 				}
 				NotifyRefreshList();
			}
		}

	};
	protected boolean needRefreshList;
	private final OpenfireNetService mOpenfireService;
	public void onCreate() {
		super.onCreate();
		if(mOpenfireService ==null || mOpenfireService.mConnection == null)
		{
			this.stopSelf();
			return;
		}
		mConnection = mOpenfireService.mConnection;
		roster = mConnection.getRoster();
//		Connection.DEBUG_ENABLED = true;
		Roster.setDefaultSubscriptionMode(Roster.SubscriptionMode.accept_all);
		IntentFilter filter = new IntentFilter(); // 和广播中Intent的action对应
		filter.addAction(getResources().getString(R.string.OPENFIRE_ACTION_REQ_LOGIN));
		filter.addAction(getResources().getString(R.string.OPENFIRE_ACTION_REQ_LOGOUT));
        registerReceiver(br, filter);
        setRosterListener();
        roster.reload();
        NotifyRefreshList();
		//好友申请监听
		getXMPPConnection().removePacketListener(checkNew);
		getXMPPConnection().addPacketListener(checkNew, checkNewFilter);
	};
	private XMPPConnection getXMPPConnection() {
		// TODO Auto-generated method stub
		return mConnection;
	}
	PacketFilter checkNewFilter = new PacketFilter() {
		
		@Override
		public boolean accept(Packet packet) {
			if(packet instanceof Presence && ((Presence) packet).getType() == Type.subscribe)
				return true;
			else
				return false;
		}
	};
	PacketListener checkNew = new PacketListener() {
		
		@Override
		public void processPacket(Packet packet) {
			Presence presence = (Presence) packet;
			if(presence.getType() == Type.subscribe)
			{
				if(roster!=null)
				{
					if(roster.contains(presence.getFrom()))
					{
						Presence subscription = new Presence(Presence.Type.subscribe);
						subscription.setFrom(FrCall.user.getUserId());
						subscription.setTo(presence.getFrom());
						getXMPPConnection().sendPacket(subscription);
						return;
					}
				}
				toastText = "";
				
				SystemMessage message;
				{
					message = new SystemMessage(FrCall.user.getUserId(),presence.getFrom(),presence.getTo(),presence.getType().toString(),true);
					BaseScreen.sysDB.insert(message);
					Main.sMsgCount++;
				}
				ListHander.sendEmptyMessage(SCREEN_HOME_HANDLE_REFRESH_NEW_MSG);
			}	
		}
	};
	private void setRosterListener(){
		roster.addRosterListener(rosterListener);
	}
	private void NotifyRefreshList(){
		Intent intent = new Intent();
		intent.setAction(getResources().getString(R.string.OPENFIRE_ACTION_NOTIFY_REFRESH_ROSTER));
		intent.putExtra(getResources().getString(R.string.REFRESH_ROSTER_LIST), true);
		sendBroadcast(intent);
	}
	@Override
	public void onDestroy() {
		try {
			if(br!=null)
				unregisterReceiver(br);
		} catch (Exception e) {
//			e.printStackTrace();
		}
		super.onDestroy();
	}
	public OpenfireRosterService() {
    	mOpenfireService = ((Engine)Engine.getInstance()).getOpenfireService();
	}
	@Override
	public void onStart(Intent intent, int startId) {
		if(mOpenfireService ==null || mOpenfireService.mConnection == null)
		{
			this.stopSelf();
			return;
		}
		super.onStart(intent, startId);
	}

	final public static int SCREEN_HOME_HANDLE_REFRESH_LIST_VIEW = 0;
	final public static int SCREEN_HOME_HANDLE_TOAST_SHOW_LIST = 2;
	final public static int SCREEN_HOME_HANDLE_REFRESH_NEW_MSG = 3;
	final public static int SCREEN_HOME_HANDLE_FILE_TRANSFER = 4;
	public static String toastText = "";
	public static int toastTime = Toast.LENGTH_SHORT;
	private Handler ListHander = new Handler() {
		
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case SCREEN_HOME_HANDLE_REFRESH_NEW_MSG:
				Main.mTVMsgCount.setText(Main.sMsgCount + "");
				Main.mTVMsgCount.setVisibility(View.VISIBLE);
				Main.mTVMsgCount.invalidate();
				break;
			default:
				// do something11. break;
			}
		}
	};
	
	
	
	public IBinder onBind(Intent intent) {
		return serviceBinder;
	}
}
